package com.xltx.weibo.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.xltx.weibo.constant.SinaConstant;
import com.xltx.weibo.model.SinaUserInfo;
import com.xltx.weibo.model.SocialUser;
import com.xltx.weibo.properties.WeiboProperties;
import com.xltx.weibo.service.WeiboService;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuyc
 * @ClassName WeiboServiceImpl
 * @Description
 * @Date 2021/12/21 17:00
 */
@Service
public class WeiboServiceImpl implements WeiboService {

    Log log = LogFactory.get(WeiboServiceImpl.class);

    @Resource
    private WeiboProperties weiboProperties;


    public String authorize() {
        return SinaConstant.AUTHORIZE
                .replace("CLIENT_ID", weiboProperties.getAppKey())
                .replace("REDIRECT_URI", weiboProperties.getRedirectUri());
    }

    @Override
    public SocialUser weiboAuth(@NonNull String code) {
        String url = SinaConstant.ACCESS_TOKEN.replace("CLIENT_ID", weiboProperties.getAppKey())
                .replace("CLIENT_SECRET", weiboProperties.getAppSecret())
                .replace("REDIRECT_URI", weiboProperties.getRedirectUri())
                .replace("CODE", code);
        String result = HttpUtil.get(url);
        try {
            return JSONUtil.toBean(result, SocialUser.class);
        } catch (Exception e) {
            log.error("weiboAuth:{}", e.getMessage());
            return null;
        }
    }

    @Override
    public SinaUserInfo getUserInfo(String accessToken, String uid) {
        if ("".equals(accessToken) || accessToken == null) {
            return null;
        }
        return getUserInfo(accessToken, uid, null);
    }

    @Override
    public SinaUserInfo getUserInfo(String accessToken, String uid, String screenName) {
        String url = SinaConstant.USER_INFO.replace("ACCESS_TOKEN", accessToken)
                .replace("UID", uid)
                .replace("SCREEN_NAME", screenName);
        String result = HttpUtil.get(url);
        try {
            return JSONUtil.toBean(result, SinaUserInfo.class);
        } catch (Exception e) {
            log.error("getUserInfo:{}", e.getMessage());
            return null;
        }
    }
}
